package com.hb.trade.api.push.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.jcraft.jsch.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.Vector;


public class SFTPUtils {
    private static ChannelSftp sftp;
    private static SFTPUtils instance = null;
    private SFTPUtils() {
    }
    public static SFTPUtils getInstance() {
        if (sftp == null || sftp.isClosed() || !sftp.isClosed()) {
            synchronized(SFTPUtils.class){
                instance = new SFTPUtils();
                sftp = instance.connect(ConstantUtil.SFTP_HOSTNAME, ConstantUtil.PORT, ConstantUtil.USERNAME, ConstantUtil.PASSWORD);   //获取连接
            }
        }
        return instance;
    }

    /**
     * 连接sftp服务器
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public ChannelSftp connect(String host, int port, String username, String password) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
        }
        return sftp;
    }

    /**
     * 上传文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     */
    public boolean upload(String directory, String uploadFile) throws IOException, SftpException {
        //将文件读入文件流
        InputStream inStream = getInputStream(uploadFile);
        try {
            sftp.cd(directory);
            uploadFile = FileUtil.getName(uploadFile).replaceAll("-","");
            sftp.put(inStream, uploadFile);
        } catch (SftpException e) {
            e.printStackTrace();
            return false;
        } finally {
            inStream.close();
        }
        return true;
    }

    /**
     *
     * @Description: 得到流的MD5
     * @Author: zhongdl
     * @Date:2022/2/23 9:42
     * @param uploadFile:
     * @return: {@link String }
     **/
    public static String getMD5(String uploadFile) throws IOException {
        InputStream inStream  = getInputStream(uploadFile);
        String md5;
        try {
            //将文件读入文件流
            md5 = DigestUtils.md5Hex(inStream);
        } finally {
            inStream.close();
        }
        return md5;
    }

    public static InputStream getInputStream(String uploadFile){

        try {
            if(StrUtil .isEmpty(uploadFile)){
                return null;
            }
            URL fileurl = new URL(uploadFile);
            HttpURLConnection urlc = (HttpURLConnection) fileurl.openConnection();
            urlc.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            urlc.setRequestProperty("Accept-Language", "zh-CN");
            //将文件读入文件流
            InputStream inStream = urlc.getInputStream();
            return inStream;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     */
    public File download(String directory, String downloadFile, String saveFile) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            sftp.get(downloadFile, fileOutputStream);
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 下载文件
     *
     * @param downloadFilePath 下载的文件完整目录
     * @param saveFile     存在本地的路径
     */
    public File download(String downloadFilePath, String saveFile) {
        try {
            int i = downloadFilePath.lastIndexOf('/');
            if (i == -1) {
                return null;
            }
            sftp.cd(downloadFilePath.substring(0, i));
            File file = new File(saveFile);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
        }
    }

    public void disconnect() {
        try {
            sftp.getSession().disconnect();
        } catch (JSchException e) {
        }
        sftp.quit();
        sftp.disconnect();
    }

    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     * @throws SftpException
     */
    public Vector<ChannelSftp.LsEntry> listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    /**
     * @Description:    上传
     * @Author:         Chen Xinmin
     * @CreateDate:     2020-7-6 上午 08:58
     */
    public static boolean uploadFile(String uploadFile) throws IOException, SftpException {
        if(StrUtil.isEmpty(uploadFile)){
            return false;
        }
        SFTPUtils sf = SFTPUtils.getInstance();
        return sf.upload(ConstantUtil.PATHNAME, uploadFile);    //上传文件
    }

    public static void main(String[] args) throws IOException, SftpException {
            new Thread(()->{
                for (int i = 0; i < 10; i++) {
                    SFTPUtils sf = SFTPUtils.getInstance();
                    try {
                        sf.upload(ConstantUtil.PATHNAME, "http://ddzb-agent.duoduozb.com/d8d27cdc72774946b98c3675a6e25944.pdf");    //上传文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }

                    //下载
                    //sf.download(directory, "2.png", "C:\\Users\\hp\\Desktop\\1212.png");
                    //删除
                    //File download = sf.download("/home/1.png", "C:\\Users\\hp\\Desktop\\122221.png");
                    //sf.delete(directory, deleteFile); //删除文件

                    Vector<ChannelSftp.LsEntry> files = null;        //查看文件列表
                    try {
                        files = sf.listFiles(ConstantUtil.PATHNAME);
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }
                    for (ChannelSftp.LsEntry file : files) {
                        System.out.println("###\t" + file.getFilename());
                    }
                }
            }).start();
    }
}
